<template>
  <div>
    <el-cascader
      ref="cascader"
      v-model="categoryId"
      :options="categoryList"
      style="width: 100%"
      :props="propsOptions"
      clearable
      filterable
      default-first-option
      :placeholder="$t('common.placeholderSelect')"
      @change="handleCategoryChange"
      @visible-change="visibleChange"
    />
  </div>
</template>
<script>
import request from '@/utils/request.js';
export default {
  name: 'CascaderComponent',
  props: {
    url: {
      type: String,
      default: '',
    },
    params: {
      type: Object,
      default() {
        return {};
      },
    },
    // 取值，获取返回参数结构
    returnData: {
      type: [Function, String],
      default: '',
    },
    propsOptions: {
      type: Object,
      default() {
        return {};
      },
    },
    // 是否返回所有节点值
    isReturnAll: {
      type: Boolean,
      default: false,
    },
    rowKey: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      categoryId: '',
      categoryList: [],
      loading: false,
    };
  },
  methods: {
    handleCategoryChange(v) {
      if (!this.isReturnAll) {
        this.$emit('input', v[v.length - 1]);
      } else {
        this.$emit('input', v);
      }
      try {
        var l = this.$refs.cascader.getCheckedNodes()[0].label;
      } catch (error) {
        l = '';
      }
      this.$emit('change', {
        value: l,
        label: this.rowKey,
      });
    },
    _request(data) {
      return request({
        url: this.url,
        method: 'post',
        data,
      });
    },
    visibleChange(v) {
      if (v && this.categoryList.length === 0) {
        this.getList();
      }
    },
    getList() {
      if (!this.url) return;
      this.loading = true;
      // 列表查询
      this._request({
        ...this.params,
      })
        .then((res) => {
          if (typeof this.returnData === 'function') {
            this.categoryList = this.returnData(res.data);
          } else {
            this.categoryList = res.data;
          }
          this.loading = false;
          this.total = res.total;
          if (this.isReturnTotal) {
            this.$emit('returnTotal', res.total);
          }
        })
        .catch(() => {
          this.categoryList = [];
          this.loading = false;
        });
    },
  },
};
</script>
